package com.example.demo.service.impl;

import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author zhangs
 * @version v1.0
 * @decription
 * @date 2021/4/7 0:00
 **/
@Service
public class UserServiceImpl implements UserService {
    private UserDao userDao;

    @Autowired
    public void setUserDao(final UserDao userDao) {
        this.userDao = userDao;
    }

    // 标识读缓存操作
    @Cacheable("userList")
    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    // 写入缓存，key一般为user.id
    @CachePut(cacheNames = {"user"}, key = "#user.id")
    @Transactional
    @Override
    public User saveUser(User user) {
        return userDao.save(user);
    }

    // 标注在delete、update方法上面
    @CacheEvict(cacheNames = {"user"}, key = "#id")
    @Transactional
    @Override
    public int updatePassword(Long id, String password) {
        return userDao.updatePassword(id, password);
    }

    // 如果缓存存在，直接读取缓存值，如果缓存不存在调用目标方法并将方法返回值放入缓存
    @Cacheable(cacheNames = {"user"}, key = "#id")
    @Override
    public User findOne(Long id) {
        return userDao.getOne(id);
    }
}
